<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>云链AI文档 - 阅读</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <!-- PDF.js 库 -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
  <style>
    body {
      font-family: 'Inter', sans-serif;
    }
    .toc-item {
      transition: all 0.2s;
    }
    .toc-item:hover {
      background-color: #F3F4F6;
    }
    .toc-item.active {
      color: #7C3AED;
      background-color: #F5F3FF;
    }
    .tool-button {
      transition: all 0.2s;
    }
    .tool-button:hover {
      background-color: #F3F4F6;
      color: #7C3AED;
    }
    .tool-button.active {
      color: #7C3AED;
      background-color: #F5F3FF;
    }
    /* 加载动画 */
    .loading-spinner {
      animation: spin 1s linear infinite;
    }
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    /* PDF 查看器样式 */
    #pdf-viewer {
      width: 100%;
      height: 100%;
    }
    .pdf-page {
      margin-bottom: 20px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    /* 文档内容样式 */
    .document {
      max-width: 800px;
      margin: 0 auto;
      line-height: 1.6;
    }
    .document h1 {
      font-size: 2em;
      font-weight: 700;
      margin: 1.5em 0 1em;
    }
    .document h2 {
      font-size: 1.5em;
      font-weight: 600;
      margin: 1.2em 0 0.8em;
    }
    .document h3 {
      font-size: 1.25em;
      font-weight: 600;
      margin: 1em 0 0.6em;
    }
    .document p {
      margin: 1em 0;
    }
    .document table {
      width: 100%;
      border-collapse: collapse;
      margin: 1em 0;
    }
    .document th,
    .document td {
      border: 1px solid #e5e7eb;
      padding: 0.75em;
      text-align: left;
    }
    .document th {
      background-color: #f9fafb;
      font-weight: 600;
    }
    .document img {
      max-width: 100%;
      height: auto;
      margin: 1em 0;
    }
    .document pre {
      background-color: #f3f4f6;
      padding: 1em;
      border-radius: 0.375rem;
      overflow-x: auto;
      margin: 1em 0;
    }
    .document code {
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
      font-size: 0.875em;
      background-color: #f3f4f6;
      padding: 0.2em 0.4em;
      border-radius: 0.25rem;
    }
    @keyframes fadeInOut {
      0% { opacity: 0; transform: translateY(-10px); }
      10% { opacity: 1; transform: translateY(0); }
      90% { opacity: 1; transform: translateY(0); }
      100% { opacity: 0; transform: translateY(-10px); }
    }

    .animate-fade-in-out {
      animation: fadeInOut 3s ease-in-out;
    }
  </style>
</head>
<body class="bg-gray-50 font-sans text-gray-700">
  <!-- 顶部工具栏 -->
  <header class="fixed top-0 left-0 right-0 h-12 bg-white border-b border-gray-200 flex items-center justify-between px-4 z-50">
    <div class="flex items-center space-x-4">
      <a href="/space.html" class="text-gray-600 hover:text-purple-600 transition-colors">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
        </svg>
      </a>
      <div class="flex items-center space-x-2">
        <button id="prev-page" class="text-gray-600 hover:text-purple-600 disabled:opacity-50 disabled:cursor-not-allowed">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
          </svg>
        </button>
        <span class="text-sm text-gray-600" id="page-info">页码加载中...</span>
        <button id="next-page" class="text-gray-600 hover:text-purple-600 disabled:opacity-50 disabled:cursor-not-allowed">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
          </svg>
        </button>
      </div>
    </div>
    <div class="flex items-center space-x-4">
      <button class="text-gray-600 hover:text-purple-600 transition-colors">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
      </button>
      <button id="convert-markdown" class="text-gray-600 hover:text-purple-600 transition-colors" title="转换为Markdown">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
      </button>
      <button id="download-button" class="text-gray-600 hover:text-purple-600 transition-colors">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
        </svg>
      </button>
      <div class="flex items-center space-x-2 text-sm">
        <select id="zoom-select" class="border rounded px-2 py-1 text-sm">
          <option value="0.5">50%</option>
          <option value="0.75">75%</option>
          <option value="1" selected>100%</option>
          <option value="1.25">125%</option>
          <option value="1.5">150%</option>
          <option value="2">200%</option>
        </select>
      </div>
    </div>
  </header>

  <!-- 主要内容区域 -->
  <div class="flex h-screen pt-12">
    <!-- 中间内容区域 -->
    <main class="flex-1 overflow-y-auto bg-white relative">
      <!-- 加载状态 -->
      <div id="loading-indicator" class="absolute inset-0 bg-white bg-opacity-90 flex items-center justify-center z-50">
        <div class="text-center">
          <svg class="loading-spinner w-10 h-10 text-purple-600 mx-auto mb-4" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <p class="text-gray-600">文档加载中...</p>
        </div>
      </div>

      <!-- 错误提示 -->
      <div id="error-message" class="hidden absolute inset-0 bg-white flex items-center justify-center">
        <div class="text-center">
          <svg class="w-12 h-12 text-red-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
          <p class="text-red-600 font-medium mb-2">加载失败</p>
          <p class="text-gray-500 text-sm" id="error-details"></p>
          <button onclick="loadFileContent()" class="mt-4 text-purple-600 hover:text-purple-700 font-medium">重试</button>
        </div>
      </div>

      <!-- 文件内容容器 -->
      <div id="content-container" class="max-w-4xl mx-auto px-8 py-6">
        <article class="prose prose-sm max-w-none">
          <!-- 文件内容将通过 JavaScript 动态加载 -->
        </article>
      </div>

      <!-- PDF 查看器容器 -->
      <div id="pdf-viewer" class="hidden max-w-4xl mx-auto px-8 py-6">
        <!-- PDF 页面将通过 JavaScript 动态加载 -->
      </div>
    </main>

    <!-- 右侧工具栏 -->
    <aside class="w-64 bg-white border-l border-gray-200">
      <div class="p-4">
        <div class="flex border-b border-gray-200">
          <button class="tool-button flex-1 text-center py-2 text-sm font-medium active">导读</button>
          <button class="tool-button flex-1 text-center py-2 text-sm font-medium">对话</button>
          <button class="tool-button flex-1 text-center py-2 text-sm font-medium">思维导图</button>
          <button class="tool-button flex-1 text-center py-2 text-sm font-medium">笔记</button>
          <button class="tool-button flex-1 text-center py-2 text-sm font-medium">改写</button>
        </div>
        <div class="mt-4">
          <div class="flex items-center justify-between mb-2">
            <span class="text-sm font-medium">精彩要点</span>
            <button class="text-sm text-purple-600">全文速读</button>
          </div>
          <div class="space-y-4" id="highlights-container">
            <!-- 要点将通过 JavaScript 动态加载 -->
            <div class="text-gray-400 text-sm p-4 text-center">要点分析中...</div>
          </div>
        </div>
      </div>
    </aside>
  </div>

  <script>
    // 获取URL参数中的文件ID
    const urlParams = new URLSearchParams(window.location.search);
    const fileId = urlParams.get('id');

    // 当前文件信息
    let currentFile = null;
    let currentPage = 1;
    let totalPages = 1;
    let pdfDoc = null;

    // 显示加载状态
    function showLoading() {
      document.getElementById('loading-indicator').classList.remove('hidden');
      document.getElementById('error-message').classList.add('hidden');
      document.getElementById('content-container').classList.add('hidden');
      document.getElementById('pdf-viewer').classList.add('hidden');
    }

    // 隐藏加载状态
    function hideLoading() {
      document.getElementById('loading-indicator').classList.add('hidden');
    }

    // 显示错误信息
    function showError(message) {
      document.getElementById('loading-indicator').classList.add('hidden');
      document.getElementById('error-message').classList.remove('hidden');
      document.getElementById('error-details').textContent = message;
    }

    // 更新页码信息
    function updatePageInfo() {
      const pageInfo = document.getElementById('page-info');
      pageInfo.textContent = `${currentPage} / ${totalPages}`;
      
      // 更新翻页按钮状态
      document.getElementById('prev-page').disabled = currentPage <= 1;
      document.getElementById('next-page').disabled = currentPage >= totalPages;
    }

    // 渲染PDF页面
    async function renderPage(pageNumber) {
      try {
        const page = await pdfDoc.getPage(pageNumber);
        const viewport = page.getViewport({ scale: 1 });
        
        // 创建canvas
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        canvas.className = 'pdf-page mx-auto';

        // 渲染PDF内容
        const renderContext = {
          canvasContext: context,
          viewport: viewport
        };
        await page.render(renderContext).promise;

        // 清空之前的内容
        const pdfViewer = document.getElementById('pdf-viewer');
        pdfViewer.innerHTML = '';
        pdfViewer.appendChild(canvas);
        
        currentPage = pageNumber;
        updatePageInfo();
      } catch (error) {
        console.error('Error rendering PDF page:', error);
        showError('PDF页面渲染失败');
      }
    }

    // 处理不同类型的文件内容
    async function handleFileContent(file) {
      const contentContainer = document.getElementById('content-container');
      const pdfViewer = document.getElementById('pdf-viewer');

      try {
        switch (file.format.toLowerCase()) {
          case 'pdf':
            // 加载 PDF
            contentContainer.classList.add('hidden');
            pdfViewer.classList.remove('hidden');
            
            const pdfData = atob(file.content);
            pdfDoc = await pdfjsLib.getDocument({ data: pdfData }).promise;
            totalPages = pdfDoc.numPages;
            await renderPage(1);
            break;

          case 'docx':
          case 'doc':
            // 显示 Word 文档
            contentContainer.classList.remove('hidden');
            pdfViewer.classList.add('hidden');
            contentContainer.querySelector('article').innerHTML = `
              <h1 class="text-2xl font-bold mb-8">${file.fileName}</h1>
              <div class="space-y-4">${file.htmlContent || '文档内容加载中...'}</div>
            `;
            break;

          default:
            // 显示纯文本
            contentContainer.classList.remove('hidden');
            pdfViewer.classList.add('hidden');
            contentContainer.querySelector('article').innerHTML = `
              <h1 class="text-2xl font-bold mb-8">${file.fileName}</h1>
              <div class="space-y-4 whitespace-pre-wrap">${file.content}</div>
            `;
        }

        // 更新目录
        updateTableOfContents(file);
        // 更新精彩要点
        updateHighlights(file);
      } catch (error) {
        console.error('Error handling file content:', error);
        showError('文件内容处理失败');
      }
    }

    // 更新目录
    function updateTableOfContents(file) {
      // 移除目录更新功能
    }

    // 更新精彩要点
    function updateHighlights(file) {
      const highlightsContainer = document.getElementById('highlights-container');
      if (file.highlights && file.highlights.length > 0) {
        highlightsContainer.innerHTML = file.highlights.map((highlight, index) => `
          <div class="p-3 bg-gray-50 rounded-lg">
            <div class="flex items-start space-x-2">
              <span class="text-purple-600 font-medium">${index + 1}.</span>
              <p class="text-sm text-gray-600">
                "${highlight.content}"
                <br>
                <span class="text-gray-400 text-xs">${highlight.description}</span>
              </p>
            </div>
          </div>
        `).join('');
      } else {
        highlightsContainer.innerHTML = '<div class="text-gray-400 text-sm p-4 text-center">正在分析文档要点...</div>';
      }
    }

    // 加载文件内容
    async function loadFileContent() {
      if (!fileId) {
        showError('未找到文件ID');
        return;
      }

      showLoading();

      try {
        const response = await fetch(`/api/files/${fileId}`);
        const result = await response.json();

        if (result.success) {
          currentFile = result.data;
          // 更新页面标题
          document.title = `云链AI文档 - ${currentFile.fileName}`;
          // 处理文件内容
          await handleFileContent(currentFile);
          hideLoading();
        } else {
          showError(result.message || '加载失败');
        }
      } catch (error) {
        console.error('Error loading file:', error);
        showError('网络错误，请稍后重试');
      }
    }

    // 事件监听器
    document.getElementById('prev-page').addEventListener('click', () => {
      if (currentPage > 1) {
        renderPage(currentPage - 1);
      }
    });

    document.getElementById('next-page').addEventListener('click', () => {
      if (currentPage < totalPages) {
        renderPage(currentPage + 1);
      }
    });

    document.getElementById('zoom-select').addEventListener('change', (e) => {
      const scale = parseFloat(e.target.value);
      // TODO: 实现缩放功能
    });

    document.getElementById('download-button').addEventListener('click', () => {
      if (currentFile) {
        // 创建下载链接
        const link = document.createElement('a');
        link.href = `/api/files/download/${currentFile.id}`;
        link.download = currentFile.fileName;
        link.click();
      }
    });

    // 目录项点击事件
    document.querySelectorAll('.toc-item').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        document.querySelectorAll('.toc-item').forEach(i => i.classList.remove('active'));
        item.classList.add('active');
      });
    });

    // 工具栏按钮点击事件
    document.querySelectorAll('.tool-button').forEach(button => {
      button.addEventListener('click', () => {
        document.querySelectorAll('.tool-button').forEach(b => b.classList.remove('active'));
        button.classList.add('active');
      });
    });

    // 初始化 PDF.js
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js';

    // 页面加载完成后加载文件内容
    if (fileId) {
      loadFileContent();
    } else {
      showError('未找到文件ID');
    }

    // 转换为Markdown
    async function convertToMarkdown() {
      if (!currentFile) return;

      try {
        showLoading();
        
        const response = await fetch(`/api/files/${currentFile.id}/convert/markdown`, {
          method: 'POST'
        });
        
        if (!response.ok) {
          throw new Error('转换失败');
        }
        
        const result = await response.json();
        
        if (result.success) {
          // 创建下载链接
          const blob = new Blob([result.data.content], { type: 'text/markdown' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = `${currentFile.fileName.split('.')[0]}.md`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
          
          // 显示成功提示
          showSuccessMessage('文档已成功转换为Markdown格式');
        } else {
          throw new Error(result.message || '转换失败');
        }
      } catch (error) {
        console.error('Error converting to markdown:', error);
        showError(error.message || '转换失败，请稍后重试');
      } finally {
        hideLoading();
      }
    }

    // 显示成功提示
    function showSuccessMessage(message) {
      const successDiv = document.createElement('div');
      successDiv.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-fade-in-out';
      successDiv.textContent = message;
      document.body.appendChild(successDiv);
      
      setTimeout(() => {
        successDiv.remove();
      }, 3000);
    }

    // 添加转换按钮事件监听
    document.getElementById('convert-markdown').addEventListener('click', convertToMarkdown);
  </script>
</body>
</html> 